from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from ai_platform.services.sync_manager import sync_wiki_data
import logging
import json

router = APIRouter(prefix="/api/wiki", tags=["wiki同步"])
logger = logging.getLogger(__name__)

class WikiSyncRequest(BaseModel):
    knowledge_base_id: str
    root_page_id: str

@router.post("/sync-debug")
async def sync_wiki_debug(request: Request):
    """调试接口，查看原始请求数据"""
    try:
        body = await request.body()
        logger.info(f"原始请求体: {body}")
        
        if body:
            body_str = body.decode('utf-8')
            logger.info(f"请求体字符串: {body_str}")
            
            try:
                json_data = json.loads(body_str)
                logger.info(f"解析后的JSON: {json_data}")
                return {"success": True, "data": json_data}
            except json.JSONDecodeError as e:
                logger.error(f"JSON解析错误: {e}")
                return {"success": False, "error": str(e)}
        else:
            logger.warning("请求体为空")
            return {"success": False, "error": "请求体为空"}
    except Exception as e:
        logger.exception(f"调试接口异常: {e}")
        return {"success": False, "error": str(e)}

@router.post("/sync")
async def sync_wiki(raw_request: Request):
    """
    同步wiki数据到指定知识库
    
    Args:
        raw_request: 原始请求对象
    
    Returns:
        同步状态信息
    """
    try:
        # 手动解析请求体
        body = await raw_request.body()
        logger.info(f"原始请求体: {body}")
        
        if not body:
            raise HTTPException(status_code=400, detail="请求体不能为空")
        
        try:
            body_str = body.decode('utf-8')
            logger.info(f"请求体字符串: {body_str}")
            json_data = json.loads(body_str)
            logger.info(f"解析后的JSON: {json_data}")
        except json.JSONDecodeError as e:
            logger.error(f"JSON解析错误: {e}")
            raise HTTPException(status_code=400, detail=f"JSON格式错误: {str(e)}")
        
        # 验证必需字段
        if 'knowledge_base_id' not in json_data:
            raise HTTPException(status_code=400, detail="缺少knowledge_base_id字段")
        if 'root_page_id' not in json_data:
            raise HTTPException(status_code=400, detail="缺少root_page_id字段")
        
        knowledge_base_id = json_data['knowledge_base_id']
        root_page_id = json_data['root_page_id']
        
        logger.info(f"开始同步wiki数据 - 知识库ID: {knowledge_base_id}, 根页面ID: {root_page_id}")
        
        # 调用异步同步方法
        updated_pages = await sync_wiki_data(knowledge_base_id, root_page_id)
        
        logger.info(f"wiki数据同步完成 - 更新了 {updated_pages} 个页面")
        
        return {
            "success": True,
            "message": "正在同步wiki数据，请稍后查看",
            "data": {
                "knowledge_base_id": knowledge_base_id,
                "root_page_id": root_page_id,
                "updated_pages": updated_pages
            }
        }
        
    except HTTPException:
        raise
    except ValueError as e:
        logger.error(f"参数错误: {e}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.exception(f"同步wiki数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")
